package com.heima.comment.service.Impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.article.IArticleClient;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.comment.controller.CommentController;
import com.heima.comment.service.CommentManageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.app.ArticlePageDto;
import com.heima.model.common.dtos.comment.CommentPageDto;
import com.heima.model.common.dtos.common.PageResponseResult;
import com.heima.model.common.dtos.common.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.vo.CommentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CommentManageServiceImpl implements CommentManageService {
    @Autowired
    private IArticleClient articleClient;
    @Override
    public ResponseResult findAll(CommentPageDto commentPageDto) {
        //检验参数
        if(commentPageDto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ArticlePageDto articlePageDto = new ArticlePageDto();
        BeanUtils.copyProperties(commentPageDto, articlePageDto);
        //获取分页后的所有信息
        ResponseResult response = articleClient.findAll(articlePageDto);
        List<CommentVo> commentVos = new ArrayList<>();
        if(response.getCode()!=200) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"未找到发布的文章信息");
        }
        String jsonData =(String) response.getData();
        PageResponseResult pageResponseResult = JSON.parseObject(jsonData, PageResponseResult.class);
        //获取app端发布的文章信息
        jsonData = (String)pageResponseResult.getData();
        List<ApArticle> apArticles = JSON.parseArray(jsonData, ApArticle.class);

        for (ApArticle apArticle : apArticles) {
            CommentVo commentVo =CommentVo
                    .builder()
                    .comments(apArticle.getComment())
                    .createTime(apArticle.getCreatedTime())
                    .isComment(true)
                    .title(apArticle.getTitle())
                    .id(String.valueOf(apArticle.getId()))
                    .build();
            commentVos.add(commentVo);
        }
        //封装响应数据
        pageResponseResult.setData(commentVos);
        pageResponseResult.setCurrentPage(pageResponseResult.getCurrentPage());
        pageResponseResult.setTotal(pageResponseResult.getTotal());
        pageResponseResult.setSize(pageResponseResult.getSize());
        return ResponseResult.okResult(pageResponseResult);
    }
}
